<?php
namespace My\Controller;

use Utuo\BackgroundController;

class WechatMenuController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle('微信菜单管理');
		$this->setActionTitle(array(
				'index' => '微信菜单列表',
				'add' => '添加微信菜单',
				'modify' => '修改微信菜单',
				'recycle' => '回收站'
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle'
            
		));
		/* 设置链接导航 */
		$topMenuLists = M('WechatMenu')->where('pid=0 AND is_deleted=0 AND cid=%d', $this->aid)->getField('id,name');
		$this->setLinkNavTitle('菜单分类');
		$this->setLinkNav('顶级菜单', U('My/WechatMenu/index'));
		foreach ($topMenuLists as $id => $name) {
			$this->setLinkNav($name, U('WechatMenu/index?pid=' . $id));
		}
	}
	
	// 菜单列表
	public function indexAction() {
		$this->getLists(0);
	}
	
	// 回收站
	public function recycleAction() {
		$this->getLists(1, false);
	}
	
	// 获取列表
	private function getLists($is_deleted, $l=true) {
		$page = $this->getPage();
		$pagesize = $this->getPageSize();
		$pid = I('pid', 0, 'intval');
		$condition = array(
				'cid' => $this->aid,
				'is_deleted' => $is_deleted,
				'pid' => $pid
		);
		if($l===false) unset($condition['pid']);
		$wechatMenuLists = M('WechatMenu')->where($condition)->limit($pagesize)->page($page)->order('sort')->select();
		$wechatMenuCount = M('WechatMenu')->where($condition)->count();
		$this->assign('wechatMenuLists', $wechatMenuLists);
		$this->showPage($wechatMenuCount, $pagesize);
		$this->display();
	}
	
	// 添加菜单
	public function addAction() {
		$d = D('WechatMenu');
		$topMenu = M('WechatMenu')->where('pid=0 AND is_deleted=0 AND cid=%d', $this->aid)->getField('id,name');
		$topMenuOptions = $this->getOption($topMenu, null, '顶级菜单');
		$this->assign('menuTypesOptions', $this->getOption($d->menuTypes, '', '==请选择回复类型=='));
		$this->assign('topMenuOptions', $topMenuOptions);
		$this->display("save");
	}
	
	// 修改菜单
	public function modifyAction() {
		$id = I('id', 0, 'intval');
      
		$d = D('WechatMenu');
        
		$wechatMenu = $d->getById($id);
     
		$topMenuOptions = $d->where('pid=0 AND is_deleted=0 AND id!=%d AND cid=%d', $id, $this->aid)->getField('id,name');
           
		$this->assign('topMenuOptions', $this->getOption($topMenuOptions, $wechatMenu['pid'], '顶级菜单'));
		$this->assign('menuTypesOptions', $this->getOption($d->menuTypes, $wechatMenu['type'], '==请选择回复类型=='));
		$this->assign('wechatMenu', $wechatMenu);
		$this->display("save");
	}
	
	// 保存修改
	public function saveAction() {
		$id = I('id', 0, "intval");
		$pid = I('pid', 0, "intval");
		$m = M("WechatMenu");
		$check = false;
		if( $id ) {
			$wechatMenu = $m->where("cid=%d and id=%d", $this->aid, $id)->find();
           
			if( $wechatMenu and $wechatMenu['pid'] != $pid and $pid == 0) { // 更新为父节点
				$check = true;
			}
		} elseif( $pid==0 ) { // 添加为父节点 
			$check = true;
		}
		if( $check ) {
			$count = M("WechatMenu")->where("cid=%d and pid=0", $this->aid)->count();
			$count >= 3 and $this->ajaxError("根级菜单只能有3个");
		}
		$this->submitPost("wechatMenu");
	}
	
	// 发布微信菜单
	public function publishMenuAction() {
		$m = M("WechatMenu");
		$menuList = $m->where(array('cid'=>$this->aid, 'status'=> 1, 'is_deleted'=> 0))->order('pid asc,sort asc')->select();
      
		$menu = array();
		if( $menuList ) {
			function toTree($menuList, &$current, $level, $pid) {
				$childs = array();
				foreach ($menuList as $v) {
					if( $v['pid']*1 == $pid ) {
						$item = array('name' => $v['name'], 'id' => $v['id']);
						if( $v['type'] == 'url' ) {
							$item['type'] = 'view';
							$item['url'] = $v['url'];
						} else {
							$item['type'] = 'click';
							$item['key'] = $v['key'];
						}
						$childs[] = $item;
					}
				}
				if( !empty($childs) ) {
					unset($current['url']); unset($current['key']); unset($current['type']);
					$current['sub_button'] = $childs;
					foreach ( $current['sub_button'] as $k => &$v) {
						toTree($menuList, $v, $level+1, $v['id']*1);
						unset($v['id']);
					}
				}
			}
			toTree($menuList, $menu, 0, 0);
		}
		if( !empty( $menu) ) {
			$menu['button'] = &$menu['sub_button'];
			unset($menu['sub_button']);
			$this->setMenu( $menu );
		} else {
			$this->ajaxError('没有菜单项。');
		}
	}
	
	private function setMenu( $menu ) {
		$wechat = M('Wechat')->where('cid=%d and pid=0', $this->aid)->find();
		if( !$wechat or empty($wechat['appid']) or empty($wechat['appsecret'])) {
			$this->ajaxError('您还没有完成开发者AppId与开发者AppSecret的设置。');
		}
		$options = array(
						'token'=> $wechat['token'], // 填写你设定的key
						'appid'=> $wechat['appid'], // 填写高级调用功能的app id
						'appsecret'=> $wechat['appsecret'], // 填写高级调用功能的密钥
				   );
		$weObj = new \Utuo\Wechat($options);
		$result = $weObj->createMenu( $menu );
		if( !$result ) {
			$this->ajaxError($weObj->errMsg);
		}
		$this->ajaxSuccess('发布成功(注:24小时后生效)!');
	}
	
	// 移除菜单
	public function removePostAction() {
		$this->ajaxRemove('wechatMenu');
	}
	
	// 恢复菜单
	public function restorePostAction() {
		$this->ajaxRestore('wechatMenu');
	}
	
	// 彻底删除
	public function deletePostAction() {
		$this->ajaxDelete('wechatMenu');
	}
}